package sealte.hvpms.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sealte.hvpms.dao.UserDAO;
import sealte.hvpms.dao.impl.UserDAOImpl;
import sealte.hvpms.pojo.UserCreate;

public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8"); 
		response.setCharacterEncoding("UTF-8");
		
		String uname = request.getParameter("username");
		String upassword = request.getParameter("userpassword");
		String email = request.getParameter("email");
		int gp_ques = Integer.parseInt(request.getParameter("gp_ques"));
		String gp_answ = request.getParameter("gp_answ");
		String verifycode = request.getParameter("verifycode");
		String rand = (String)request.getSession().getAttribute("rand");
		if(verifycode.equals(rand)){
			UserCreate uc = new UserCreate();
			uc.setName(uname);
			uc.setPassword(upassword);
			uc.setEmail(email);
			uc.setQues(gp_ques);
			uc.setAnsw(gp_answ);
			UserDAO ub = new UserDAOImpl();
			boolean isexist = ub.verifyName(uname);
			if(!isexist){
				boolean flag = ub.register(uc);
				if(flag){
					request.setAttribute("register_succeed", "注册成功，请登录。");
					request.getRequestDispatcher("index.jsp").forward(request, response);
				}else{
					request.setAttribute("message", "注册失败！！");
					request.getRequestDispatcher("register.jsp").forward(request, response);
				}
			}else{
				request.setAttribute("message_verifyname", "该账号已存在！");
				request.getRequestDispatcher("register.jsp").forward(request, response);
			}
		}else{
			request.setAttribute("message_checkcode", "验证码错误");
			request.getRequestDispatcher("register.jsp").forward(request, response);
		}
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		this.doPost(request, response);
	}
}
